package main

import "sync"

func main() {
	var wg sync.WaitGroup

	cond := sync.NewCond(&sync.Mutex{})
	data := make([]int, 0)

	wg.Add(1)
	go func() {
		defer wg.Done()

		for i := 0; i < 5; i++ {
			cond.L.Lock()
			data = append(data, i+100)
			cond.L.Unlock()

			// 唤醒一个
			cond.Signal() // 通知消费者
		}
	}()

	for i := 0; i < 5; i++ {
		wg.Add(1)
		go func(id int) {
			defer wg.Done()
			cond.L.Lock()

			// 若条件不符合，则继续等待
			for len(data) == 0 {
				cond.Wait() // 等待生产者通知
			}
			x := data[0]
			data = data[1:]
			cond.L.Unlock()
			println(id, ":", x)

		}(1)

	}

	wg.Wait()
}
